package cn.wzx.controller;

import cn.wzx.entity.Largefile;
import cn.wzx.entity.MyUser;
import cn.wzx.respJson.RespJson;
import cn.wzx.respJson.Token;
import cn.wzx.service.LargefileService;
import cn.wzx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@CrossOrigin // 允许跨域访问
@RestController
@RequestMapping("/api/fore/user")
public class UserForeController {
    @Autowired
    LargefileService largefileService;

    @Autowired
    UserService userService;

    // 更新修改密码
    @RequestMapping("/updatePwd")
    public Map<String, Object> updatePwd(String password) {
        Map<String, Object> map = new HashMap<>();
        // 获取到登录后的token，从中获取到登录者的信息，从而获取到用户ID
        MyUser user = (MyUser)Token.getUser();
        int uid = user.getId();
        map.put("id", uid);
        map.put("password", password);
        userService.update(map);
        return RespJson.pack(200, "更新密码成功", "");
    }

    // 更新用户头像
    @RequestMapping({"/updateImg"})
    public Map<String, Object> updateImg(@RequestParam(value = "img", required = false) MultipartFile file,Largefile largefile) {
        System.out.println("file=========" + file);
        if (file == null) {
            return RespJson.pack(500,"图片未上传",null);
        }
        // 获取到登录后的token，从中获取到登录者的信息，从而获取到用户ID
        MyUser user = (MyUser)Token.getUser();
        int uid = user.getId();
        Map<String, Object> map = new HashMap<>();
        map.put("id", uid);
        // 生成唯一的uuid
        String uuid = UUID.randomUUID().toString();
        if (file != null && file.getSize() > 0) {
            map.put("img", uuid);
            userService.update(map);
            try {
                // 图片添加
                largefile.setId(uuid);
                largefile.setFilename(file.getOriginalFilename());
                largefile.setContent(file.getBytes());
                largefileService.add(largefile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return RespJson.pack(200, "更新用户头像成功", uuid);
    }

    // 更新用户信息 名称和电话
    @RequestMapping("/updateInfo")
    public Map<String, Object> updateInfo(String nickname, String phone) {
        Map<String, Object> map = new HashMap<>();
        // 获取到登录后的token，从中获取到登录者的信息，从而获取到用户ID
        MyUser user = (MyUser)Token.getUser();
        int uid = user.getId();
        map.put("id", uid);
        map.put("nickname", nickname);
        map.put("phone", phone);
        userService.update(map);
        return RespJson.pack(200, "更新用户信息成功", nickname);
    }

}
